import json

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from django.core import serializers
from utils import mypage

# Create your views here.


@csrf_exempt
def index(request):
    if request.method == 'POST':
        print(request.POST)
        print(request.POST.get('username'))
        print(request.FILES)
    return render(request, 'index.html')


@csrf_exempt
def ab_json(request):
    if request.is_ajax():
        print(request.is_ajax())  # 判断请求是不是ajax请求，返回bool值
        print(request.FILES)
        print(request.body)  # b'{"username":"AK","age":19}'
        # 针对前端发送过来的json格式的数据需要手动处理
        json_bytes = request.body
        json_str = json_bytes.decode('utf-8')
        json_dict = json.loads(json_str)
        print(json_dict, type(json_dict))
        # json.loads()括号内如果传入了一个二进制格式的数据name内部自动解码再反序列化
        json_dict = json.loads(request.body)
        print(json_dict, type(json_dict))
    return render(request, 'ab_json.html')


@csrf_exempt
def ab_file(request):
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
    return render(request, 'ab_file.html')


def ab_user(request):
    user_queryset = models.User.objects.all()
    user_list = [
        {'pk': user_obj.pk, 'username': user_obj.username,
         'age': user_obj.age, 'gender': user_obj.get_gender_display()}
         for user_obj in user_queryset]
    # return render(request, 'ab_user.html', locals())
    # 序列化
    res = serializers.serialize('json', user_queryset)
    print(res)
    """
    [
    {"model": "app01.user", "pk": 1, "fields": {"username": "jason", "age": 25, "gender": 1}}, 
    {"model": "app01.user", "pk": 2, "fields": {"username": "egon", "age": 31, "gender": 2}}, 
    {"model": "app01.user", "pk": 3, "fields": {"username": "kevin", "age": 32, "gender": 3}}, 
    {"model": "app01.user", "pk": 4, "fields": {"username": "tank", "age": 40, "gender": 4}}]
    """
    # return JsonResponse(user_list, safe=False)
    return HttpResponse(res)


@csrf_exempt
def ab_pl(request):
    # # 先给book表插入1万条数据
    # # for i in range(10000):
    # #     models.Book.objects.create(title=f'第{i}本书')
    #
    # # 批量插入
    # # book_list = [models.Book(title=f'第{i}本书') for i in range(100000)]
    # # models.Book.objects.bulk_create(book_list)
    # # 再将所有的数据查询并展示到前端页面
    # # 分页
    # book_list = models.Book.objects.all()
    # all_count = book_list.count()
    # print(all_count)
    # current_page = int(request.GET.get('page', 1))
    # # 每页多少条数据
    # per_page = 10
    # # 起始位置
    # start_page = (current_page - 1) * per_page
    # # 终止位置
    # end_page = current_page * per_page
    #
    # page_count, more = divmod(all_count, per_page)
    # page_count = page_count + 1 if more else page_count
    #
    # page_html = ''
    # xxx = current_page
    # if current_page < 6:
    #     current_page = 6
    # for i in range(current_page - 5, current_page + 6):
    #     if xxx == i:
    #         page_html += f'<li class="active"><a href="?page={i}">{i}</a></li>'
    #     else:
    #         page_html += f'<li ><a href="?page={i}">{i}</a></li>'
    # book_queryset = models.Book.objects.all()[start_page:end_page]
    current_page = request.GET.get('page', 1)
    book_query_set = models.Book.objects.all()
    all_count = book_query_set.count()
    page_obj = mypage.Pagination(current_page=current_page, all_count=all_count)
    page_queryset = book_query_set[page_obj.start:page_obj.end]

    return render(request, 'ab_pl.html', locals())